package com.jone.bang.db;



import java.util.HashMap;
import java.util.Locale;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.jone.bang.model.BChannel;



public class DataProvider extends ContentProvider {
	private static final String TAG = "DataProvider";
	private static final String DATABASE_NAME ="bang.db";
	private static final int DATABASE_VER =1;
	private static final String TABLE_NAME_CHANNEL = "channel";	
    
    
    private static HashMap<String, String> channelProjectionMap;

    private static final int Channel = 0;
    

    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
	
    private DatabaseHelper mOpenHelper;
    
    static {
        sUriMatcher.addURI("com.jone.bang", "channel", Channel);

        channelProjectionMap = new HashMap<String, String>();
        channelProjectionMap.put(BChannel._ID, BChannel._ID);
        channelProjectionMap.put(BChannel.NAME, BChannel.NAME);
        channelProjectionMap.put(BChannel.KEY, BChannel.KEY);
        channelProjectionMap.put(BChannel.RSS_URL, BChannel.RSS_URL);
        channelProjectionMap.put(BChannel.COLLECTED, BChannel.COLLECTED);
        channelProjectionMap.put(BChannel.UPDATE_TIME, BChannel.UPDATE_TIME);        
    }	
	
   @Override
    public boolean onCreate() 
   	{
	   Log.i("DEMO","DataProvider>>>onCreate ");
	        mOpenHelper = new DatabaseHelper(getContext());
	        mOpenHelper.getWritableDatabase();
	        return true;
   	}


	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		  SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	       int count = 0;
	        switch (sUriMatcher.match(uri)) {
	        case Channel:
	            count = db.delete(TABLE_NAME_CHANNEL, where, whereArgs);
	            break;
	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        getContext().getContentResolver().notifyChange(uri, null);
	        return count;
	}

	@Override
	public String getType(Uri uri) {
		Log.i("DEMO","DataProvider>>> getType");
		  switch (sUriMatcher.match(uri)) {
	        case Channel:
	            return BChannel.CONTENT_TYPE_CHANNEL;
	       
	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {		
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		long rowId = 0; 
		Uri retUri = null;
		
		switch (sUriMatcher.match(uri)) {
	
		case Channel:
			rowId = db.insert(TABLE_NAME_CHANNEL, null, values);
			retUri = ContentUris.withAppendedId(BChannel.CHANNEL, rowId);
			break;		
	
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		
		return retUri;
	}



	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		
			Log.i("DEMO", "DataProvider.query....");
		
		   SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

	        switch (sUriMatcher.match(uri)) {
	        case Channel:
	        	 qb.setTables(TABLE_NAME_CHANNEL);
		         qb.setProjectionMap(channelProjectionMap);
	        	break;	       
	       
	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        // If no sort order is specified use the default
	        String orderBy;
	        if (TextUtils.isEmpty(sortOrder)) {
	            orderBy = " _id desc";
	        } else {
	            orderBy = sortOrder;
	        }

	        // Get the database and run the query
	        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
	        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

	        // Tell the cursor what uri to watch, so it knows when its source data changes
	        c.setNotificationUri(getContext().getContentResolver(), uri);
	        return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where,
			String[] whereArgs) {
		
		  SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	        int count;
	        switch (sUriMatcher.match(uri)) {
	        case Channel:
	            count = db.update(TABLE_NAME_CHANNEL, values, where, whereArgs);
	            break;	       
	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        getContext().getContentResolver().notifyChange(uri, null);
	        return count;
	}	
	
	 
	 
	 private static class DatabaseHelper extends SQLiteOpenHelper{	
			
			public DatabaseHelper(Context context) {			
				super(context, DATABASE_NAME, null, DATABASE_VER);
				Log.i(TAG,"DatabaseHelper DatabaseHelper");
			}

			@Override
			public void onCreate(SQLiteDatabase db) {			
				Log.v(TAG, "db onCreate begin------------------");
				
				StringBuffer sql = new StringBuffer();
				//频道
				sql.append("CREATE TABLE if not exists channel(");
				sql.append("_id INTEGER PRIMARY KEY AUTOINCREMENT,");
				sql.append("key varchar(30),");
				sql.append("name varchar(50),");
				sql.append("rss_url varchar(100),");
				sql.append("collected INTEGER,");
				sql.append("update_time varchar(14))");
				db.execSQL(sql.toString());				
				
				 // ---------------------------------- 插入一些默认数据
			    String hsql = "INSERT INTO channel (_id,key, name, rss_url,collected,update_time) VALUES ";		
		    	db.execSQL(hsql + "(1,'top10','今日飙升','http://top.baidu.com/rss/top10.xml',0, '');");
		    	db.execSQL(hsql + "(2,'weekhotspot','一周热点','http://top.baidu.com/rss/weekhotspot.xml',0, '');");
		    	db.execSQL(hsql + "(3,'renwu','焦点人物','http://top.baidu.com/rss/renwu.xml',0, '');");
		    	db.execSQL(hsql + "(4,'movie','热门电影','http://top.baidu.com/rss/movie.xml',0, '');");
		    	db.execSQL(hsql + "(5,'tv','热播电视','http://top.baidu.com/rss/tv.xml',0, '');");	
		    	db.execSQL(hsql + "(6,'book','畅销书','http://top.baidu.com/rss/shu.xml',0, '');");
		    	
		    	
			   
			    			    
				Log.v(TAG, "DB init success!------------------------");
			}

			@Override
			public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
				
				  
			}
			
		}

}
